package ke08;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;

public class AsyncExecDemo {

	public static void main(String[] args) throws InterruptedException {

		final Display display = new Display();
		final Shell shell = new Shell(display);
		shell.setText("AsyncExecDemo");
		shell.setLayout(new FillLayout(SWT.VERTICAL));

		final ProgressBar bar = new ProgressBar(shell, SWT.SMOOTH);
		bar.setMaximum(100);

		Button check = new Button(shell, SWT.CHECK);
		check.setText("Click me to see if GUI responds");

		Button go = new Button(shell, SWT.PUSH);
		go.setText("Start ");
		go.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {

				new Thread() {

					private int max;

					@Override
					public void run() {

						display.syncExec(new Runnable() {
							@Override
							public void run() {
								max = bar.getMaximum();
							}
						});

						for (int i = 0; i <= max; i++) {
							final int finalI = i;
							display.asyncExec(new Runnable() {
								@Override
								public void run() {
									bar.setSelection(finalI);
								}
							});

							try {
								Thread.sleep((long) (200 * Math.random()));
							} catch (InterruptedException ex) {
								ex.printStackTrace();
							}
						}
					}
				}.start();

			}

		});

		shell.pack();
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();

	}
}
